<template>
  <view class="page">
    <!-- 页头导航 -->
    <view class="header-nav">
      <view class="nav-left" @tap="goBack">
        <image
          class="back-icon"
          src="/static/icons/left_arrow.png"
          mode="aspectFit"
        ></image>
      </view>
      <view class="nav-title">编辑基本信息</view>
      <view class="nav-right">
        <button class="edit-btn" @tap="handleSubmit" :disabled="!canSubmit">
          保存
        </button>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="container">
      <!-- 表单区域 -->
      <view class="form-section">
        <!-- 公司名称（只读） -->
        <view class="form-item">
          <view class="form-label">公司名称</view>
          <view class="form-value fixed">{{ companyName || '暂无公司名称' }}</view>
        </view>

        <!-- 公司简称 -->
        <view class="form-item">
          <view class="form-label">公司简称</view>
          <input
            class="form-input"
            v-model="formData.shortName"
            placeholder="请输入公司简称（2-20个字符）"
            maxlength="20"
          />
        </view>

        <!-- LOGO -->
        <view class="form-item">
          <view class="form-label">LOGO</view>
          <view class="upload-section" @tap="chooseLogo">
            <image
              v-if="formData.logo"
              :src="formData.logo"
              class="upload-image"
              mode="aspectFit"
            ></image>
            <view v-else class="upload-placeholder">
              <text class="upload-text">点击上传LOGO</text>
            </view>
          </view>
        </view>

        <!-- 公司地址 -->
        <view class="form-item">
          <view class="form-label">公司地址</view>
          <view class="address-selector" @tap="openCitySelector">
            <text v-if="formData.address" class="selected-address">{{ formData.address }}</text>
            <text v-else class="address-placeholder">请选择公司所在城市</text>
            <text class="arrow">></text>
          </view>
        </view>

        <!-- 公司介绍 -->
        <view class="form-item">
          <view class="form-label">公司介绍</view>
          <textarea
            class="form-textarea"
            v-model="formData.introduction"
            placeholder="请输入公司介绍"
            maxlength="500"
            auto-height
          />
        </view>
      </view>
    </view>


  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { modifyCompanyInfoApi } from "@/api/company.js";
import { chooseFile, uploadFile2OSS } from "@/utils/file.js";
import { getApplyUploadSignApi } from "@/api/company.js";
// 页面参数
const companyId = ref('');
const companyName = ref('');

// 表单数据
const formData = ref({
  logo: '',
  shortName: '',
  address: '',
  introduction: ''
});

// 是否可以提交
const canSubmit = computed(() => {
  return formData.value.shortName && 
         formData.value.shortName.trim() !== '' &&
         formData.value.logo && 
         formData.value.logo.trim() !== '';
});

// 选择LOGO
const chooseLogo = async () => {
  try {
    const tempFilePath = await chooseFile({
      count: 1,
      mediaType: ["image"],
      sourceType: ["album", "camera"],
    });
    
    if (!tempFilePath) return;

    uni.showLoading({ title: "上传中..." });
    const uploadUrl = await uploadFile2OSS(
      tempFilePath,
      "company",
      getApplyUploadSignApi
    );
    formData.value.logo = uploadUrl;
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    console.log(error.message);
    
    uni.showToast({
      title: "上传失败，请重试",
      icon: "none",
    });
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!canSubmit.value) return;

  try {
    uni.showLoading({
      title: "保存中...",
      mask: true,
    });

    const submitData = {
      companyId: companyId.value,
      logo: formData.value.logo,
      shortName: formData.value.shortName,
      address: formData.value.address,
      introduction: formData.value.introduction
    };

    await modifyCompanyInfoApi(submitData);

    uni.hideLoading();
    uni.showToast({
      title: "保存成功",
      icon: "success",
    });

    // 发送事件通知公司详情页面重新获取数据
    uni.$emit('companyInfoUpdated');
    
    // 延迟返回上一页，确保事件能被正确接收
    setTimeout(() => {
      uni.navigateBack();
    }, 500);

  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || "保存失败",
      icon: "none",
    });
  }
};

// 打开城市选择器
const openCitySelector = () => {
  console.log('跳转到城市选择页面');
  uni.navigateTo({
    url: '/pages/company/citySelector'
  });
};

// 城市选择回调（供城市选择页面调用）
const onCitySelected = (city) => {
  console.log('收到城市选择结果:', city);
  formData.value.address = city.name;
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 页面加载时获取参数和初始化数据
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options.companyId) {
    companyId.value = options.companyId;
  }
  if (options.companyName) {
    companyName.value = options.companyName;
  }
  if (options.logo) {
    formData.value.logo = options.logo;
  }
  if (options.shortName) {
    formData.value.shortName = options.shortName;
  }
  if (options.address) {
    formData.value.address = options.address;
  }
  if (options.introduction) {
    formData.value.introduction = options.introduction;
  }
  
  // 监听城市选择事件
  uni.$on('citySelected', onCitySelected);
});

// 页面卸载时移除事件监听
onUnmounted(() => {
  uni.$off('citySelected', onCitySelected);
});
</script>

<style scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  width: 120rpx;
  height: 60rpx;
}

.edit-btn {
  width: 120rpx;
  height: 60rpx;
  background-color: #007aff;
  color: #fff;
  font-size: 28rpx;
  border: none;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-btn[disabled] {
  background-color: #c0c0c0;
  color: #fff;
}

.container {
  padding: 20rpx;
}

/* 表单区域样式 */
.form-section {
  background-color: #fff;
  border-radius: 8rpx;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

.form-item {
  display: flex;
  flex-direction: column;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: #fff;
  width: 100%;
  box-sizing: border-box;
}

.form-item:last-child {
  border-bottom: none;
}

.form-label {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
}

.form-input {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  border: none;
  outline: none;
  min-height: 80rpx;
  padding: 12rpx 16rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
  display: block;
  position: relative;
  z-index: 1;
}

.form-input:focus {
  border-color: #007aff;
  background-color: #fff;
  box-shadow: 0 0 0 2rpx rgba(0, 122, 255, 0.2);
}

.form-textarea {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  border: none;
  outline: none;
  min-height: 120rpx;
  line-height: 1.5;
  padding: 12rpx 16rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
  resize: none;
  display: block;
  position: relative;
  z-index: 1;
}

.form-textarea:focus {
  border-color: #007aff;
  background-color: #fff;
  box-shadow: 0 0 0 2rpx rgba(0, 122, 255, 0.2);
}

.form-value {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.form-value.fixed {
  color: #999;
}

.upload-section {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #ddd;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
  box-sizing: border-box;
  margin: 0 auto;
}

.upload-image {
  width: 200rpx;
  height: 200rpx;
  object-fit: cover;
  border-radius: 6rpx;
}

.upload-placeholder {
  text-align: center;
  color: #999;
}

.upload-text {
  font-size: 28rpx;
}

/* 地址选择器样式 */
.address-selector {
  width: 100%;
  min-height: 80rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
}

.selected-address {
  font-size: 32rpx;
  color: #333;
  flex: 1;
}

.address-placeholder {
  font-size: 32rpx;
  color: #999;
  flex: 1;
}

.arrow {
  font-size: 28rpx;
  color: #999;
  margin-left: 10rpx;
}
</style>
